//
//  MasterViewController.m
//  album
//
//  Created by 云天 李 on 12-1-12.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "MasterViewController.h"

#import "DetailViewController.h"
#import "Album.h"
#import "AlbumDB.h"

@implementation MasterViewController

@synthesize detailViewController = _detailViewController;
@synthesize editingAlbum = _editingAlbum;
@synthesize albumTitleTextField = _albumTitleTextField;
@synthesize albums = _albums;


// 编辑相册时，更改按钮的标题和样式
// 见: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
- (IBAction) changeRightBarButton
{
    if (self.editing)
    {
        // 取消列表行的可编辑状态
        self.tableView.editing = NO;
        self.tableView.allowsSelectionDuringEditing = NO;
        self.editing = NO;
        
        // 恢复按钮标题和样式
        self.navigationItem.rightBarButtonItem.title = @"编辑";
        self.navigationItem.rightBarButtonItem.style = UIBarButtonItemStyleBordered;
    }
    else
    {
        // 点击编辑按钮后，将列表的行设置为可编辑状态，点击相册名称可以修改相册
        // 点击相册名称前的红色圆形图标可以删除此相册
        self.tableView.editing = YES;
        self.tableView.allowsSelectionDuringEditing = YES;
        self.editing = YES;
        
        // 将编辑按钮标题改成“完成”，同时改变按钮样式
        self.navigationItem.rightBarButtonItem.title = @"完成";
        self.navigationItem.rightBarButtonItem.style = UIBarButtonItemStyleDone;
    }
}

// 添加、编辑相册
- (IBAction) saveAlbum
{
    // 显示一个有取消和存储按钮的UIAlertView
    // 注：message中的4个“\n”就是给下面的UITextField设置空间的
    // 如果是编辑相册名称，则显示不同的标题
    NSString *alertTitle = self.editingAlbum.albumid == 0 ? @"新建相册" : @"编辑相册";
    UIAlertView *newAlbum = [[UIAlertView alloc] initWithTitle:alertTitle
                                                       message:@"请为此相册输入名称。\n\n\n\n"
                                                      delegate:self 
                                             cancelButtonTitle:@"取消" 
                                             otherButtonTitles:@"存储"
                             , nil];
    
    // 添加一个UITextField，用于输入相册名称
    self.albumTitleTextField = [[UITextField alloc] initWithFrame:CGRectMake(12, 95, 260, 30)];  
    [self.albumTitleTextField setBackgroundColor:[UIColor whiteColor]];
    [self.albumTitleTextField setPlaceholder:@"标题"];
    // 如果是编辑相册，则输入框默认显示相册原标题
    if (self.editingAlbum.albumid != 0)
    {
        [self.albumTitleTextField setText:self.editingAlbum.title];
    }
    // 自动弹出键盘
    [self.albumTitleTextField becomeFirstResponder];
    [newAlbum addSubview:self.albumTitleTextField];  
    
    [newAlbum show];
    [newAlbum release];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	// buttonIndex == 0: 用户点击取消按钮。
    // buttonIndex == 1: 用户点击存储按钮。
    // 如果点击了存储按钮，且输入标题的话，则进行保存操作。
    // 其他情况则关闭UIAlertView，不做处理。
    // 这里未做相册同名的验证，也未作保存失败的处理；
    // 保存后，重新载入所有相册
	if (buttonIndex == 1 && self.albumTitleTextField.text.length > 0)
	{
        // 如果点击存储时，未更改名称，则不做处理
        if (![self.albumTitleTextField.text isEqualToString:self.editingAlbum.title])
        {
            self.editingAlbum.title = self.albumTitleTextField.text;
            [AlbumDB saveAlbum:self.editingAlbum];
            
            [self loadAlbums];
            [self.tableView reloadData];
        }
	}
    
    // 思考：为什么要加这一行？
    self.editingAlbum.albumid = 0;
}

// 从数据库读取所有相册
- (void) loadAlbums
{
    if (self.albums == nil)
    {
        self.albums = [NSMutableArray array];
    }
    else
    {
        [self.albums removeAllObjects];
    }
    
    self.albums = [AlbumDB fetchAlbums];
}

#pragma mark - init OR dealloc
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"相册", nil);
        
        self.navigationItem.leftBarButtonItem  = [[[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStyleBordered target:self action:@selector(saveAlbum)] autorelease];
        self.navigationItem.rightBarButtonItem  = [[[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStyleBordered target:self action:@selector(changeRightBarButton)] autorelease];
        // possibleTitles属性的含义是告诉应用程序，根据标题文字来设定按钮长度，以便可以显示出最长的那个标题
        self.navigationItem.rightBarButtonItem.possibleTitles = [NSSet setWithObjects:@"编辑", @"完成", nil];
        
        // 注，我们也可以使用下面的这行代码设置编辑/完成切换按钮
        // 此时点击此按钮，将调用方法：- (void)setEditing:(BOOL)editing animated:(BOOL)animated
        //self.navigationItem.rightBarButtonItem = self.editButtonItem;
    }
    return self;
}

- (void)dealloc
{
    [_detailViewController release];
    [_albumTitleTextField release];
    [_albums release];
    [_editingAlbum release];
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    // 当前编辑的相册
    self.editingAlbum = [[Album alloc] init];
    
    // 读取数据库中的相册记录到一个数组
    [self loadAlbums];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

#pragma mark - UITableViewDataSource
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.albums count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    Album *_album = [self.albums objectAtIndex:[indexPath row]];
    
    // Configure the cell.
    cell.textLabel.text = _album.title;
    return cell;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        Album *_album = [self.albums objectAtIndex:[indexPath row]];
        [AlbumDB deleteAlbum:_album];
        [self.albums removeObject:_album];
        
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 如果是可编辑状态，点击列表行，则是编辑相册标题
    if (self.editing)
    {
        // 获取当前编辑的相册
        self.editingAlbum = [self.albums objectAtIndex:[indexPath row]];
        [self saveAlbum];
    }
    else
    {
        
        if (!self.detailViewController) {
            self.detailViewController = [[[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil] autorelease];
        }
        
        [self.detailViewController setCurrentAlbum:[self.albums objectAtIndex:[indexPath row]]];
        
        [self.navigationController pushViewController:self.detailViewController animated:YES];
    }
}

@end
